package uk.co.hs.web.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import uk.co.hs.web.util.SessionModuleAccessibility;

/**
 * Intercepts a handler to put a module accessibility attribute into the session.  Not necessary for Java
 * code as can use @Profile annotation, but needed for JSPs.
 */
public class ModuleAccessibilityInterceptor implements HandlerInterceptor, ApplicationContextAware
{
  public static final String MODULE_ACCESSIBILITY = "moduleAccessibility";
  
  public static final String MODULE_CORE = "moduleCore";

  private ApplicationContext mCtx;

  /**
   * @see org.springframework.web.servlet.HandlerInterceptor
   * #preHandle(javax.servlet.http.HttpServletRequest,
   *            javax.servlet.http.HttpServletResponse,
   *            java.lang.Object)
   * {@inheritDoc}
   */
  public boolean preHandle(HttpServletRequest aRequest,
                           HttpServletResponse aResponse,
                           Object aHandler) throws Exception
  {

    SessionModuleAccessibility sessionModuleAccessibility = new SessionModuleAccessibility();

    //Dual Fuel
    if (mCtx.getEnvironment().acceptsProfiles(MODULE_CORE))
      sessionModuleAccessibility.setCoreAccess(Boolean.TRUE);

    aRequest.getSession().setAttribute(MODULE_ACCESSIBILITY, sessionModuleAccessibility);
    return true;
  }

  /**
   * @see org.springframework.web.servlet.HandlerInterceptor
   * #postHandle(javax.servlet.http.HttpServletRequest,
   *             javax.servlet.http.HttpServletResponse,
   *             java.lang.Object,
   *             org.springframework.web.servlet.ModelAndView)
   * {@inheritDoc}
   */
  public void postHandle(HttpServletRequest aRequest,
                         HttpServletResponse aResponse,
                         Object aHandler,
                         ModelAndView aModelAndView) throws Exception
  { }

  /**
   * @see org.springframework.web.servlet.HandlerInterceptor
   * #afterCompletion(javax.servlet.http.HttpServletRequest,
   *                  javax.servlet.http.HttpServletResponse,
   *                  java.lang.Object, java.lang.Exception)
   * {@inheritDoc}
   */
  public void afterCompletion(HttpServletRequest aRequest,
                              HttpServletResponse aResponse,
                              Object aHandler,
                              Exception aException) throws Exception
  { }

  @Override
  public void setApplicationContext(ApplicationContext aCtx)
      throws BeansException
  {
    mCtx = aCtx;
  }
}
